//vuex 放一些公共的变量和方法

import Vue from "vue"
import vuex from "vuex"

Vue.use(vuex)

//创建vuex实例

const store = new vuex.Store({
    state: {
        //存储变量 购物车的数据(对象格式)
        shopcar: []
    },

    getters: {
        //相当于计算属性computed   
        shopcara(state) {
            return state.shopcar
        }
    },
    mutations: {
        //存储方法 用于改变state中的变量状态
        add(state, payload) {
            //本身存在这个数组 就找到这个对象得索引值
            var index = state.shopcar.findIndex(item => {
                return item.iid == payload.iid
            })
            state.shopcar[index].count += 1
            console.log(state.shopcar)
        },

        have(state, payload) {
            // payload.checked = true
            payload.count = 1
            state.shopcar.push(payload)
        },
    },
    actions: {
        //实现多个功能
        increment(comtext, goshop) {
            //得到详情页传来得信息后 判断是否存在与shopcar数组中 根据iid
            console.log(goshop)
            return new Promise((reslove, reject) => {
                var item = comtext.state.shopcar.some(item => {
                        return item.iid == goshop.iid
                    })
                    //要是存在得话 进入add  不存在 进入have
                if (item) {
                    comtext.commit("add", goshop)
                } else {
                    goshop.checked = true
                    comtext.commit("have", goshop)
                }
                reslove("添加成功")
            })
        }
    },

    modules: {

    }

})

export default store